package com.cgbl.cg.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.transition.*
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView.DefaultOnStateChangedListener
import com.lxj.xpopup.R
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupStatus
import com.lxj.xpopup.interfaces.OnDragChangeListener
import com.lxj.xpopup.interfaces.OnImageViewerLongPressListener
import com.lxj.xpopup.interfaces.OnSrcViewUpdateListener
import com.lxj.xpopup.photoview.PhotoView
import com.lxj.xpopup.util.*
import com.lxj.xpopup.widget.BlankView
import com.lxj.xpopup.widget.HackyViewPager
import com.lxj.xpopup.widget.PhotoViewContainer
import java.io.File

/**
 * Description: 大图预览的弹窗，使用Transition实现
 * Create by lxj, at 2019/1/22
 */
class ImagePop(context: Context) : BasePopupView(context),
    OnDragChangeListener, View.OnClickListener {

    protected var container: FrameLayout
    protected var photoViewContainer: PhotoViewContainer? = null
    protected var placeholderView: BlankView? = null
    protected var tv_pager_indicator: TextView? = null
    protected var tv_save: TextView? = null
    protected var pager: HackyViewPager? = null
    protected var argbEvaluator = ArgbEvaluator()
    protected var urls: MutableList<Any>? = ArrayList()
    protected var imageLoader: SmartGlideImageLoader? = null
    protected var srcViewUpdateListener: OnSrcViewUpdateListener? = null
    protected var position = 0
    protected var rect: Rect? = null
    protected var srcView //动画起始的View，如果为null，移动和过渡动画效果会没有，只有弹窗的缩放功能
            : ImageView? = null
    protected var snapshotView: PhotoView? = null
    protected var isShowPlaceholder = true //是否显示占位白色，当图片切换为大图时，原来的地方会有一个白色块
    protected var placeholderColor = Color.parseColor("#f1f1f1") //占位View的颜色
    protected var placeholderStrokeColor = -1 // 占位View的边框色
    protected var placeholderRadius = -1 // 占位View的圆角
    protected var isShowSaveBtn = true //是否显示保存按钮
    protected var isShowIndicator = true //是否页码指示器
    protected var isInfinite = false //是否需要无限滚动
    protected var customView: View? = null
    private lateinit var photoViewAdapter: PhotoViewAdapter
    protected var bgColor = Color.rgb(32, 36, 46) //弹窗的背景颜色，可以自定义
    var longPressListener: OnImageViewerLongPressListener? = null

    init {
        container = findViewById(R.id.container)
        if (implLayoutId > 0) {
            customView = LayoutInflater.from(getContext()).inflate(implLayoutId, container, false)
            customView?.setVisibility(INVISIBLE)
            customView?.setAlpha(0f)
            container.addView(customView)
        }
    }

    override fun getInnerLayoutId(): Int {
        return com.cgbl.cg.R.layout.app_pop_img
    }

    override fun initPopupContent() {
        super.initPopupContent()
        val ivDelete = findViewById<AppCompatImageView>(com.cgbl.cg.R.id.iv_delete)
        ivDelete.setOnClickListener {
            LogUtils.e(urls)
            urls?.removeAt(realPosition)
            photoViewAdapter.notifyDataSetChanged()

        }
        tv_pager_indicator = findViewById(R.id.tv_pager_indicator)
        tv_save = findViewById(R.id.tv_save)
        placeholderView = findViewById(R.id.placeholderView)
        photoViewContainer = findViewById(R.id.photoViewContainer)
        photoViewContainer?.setOnDragChangeListener(this)
        pager = findViewById(R.id.pager)
        photoViewAdapter = PhotoViewAdapter()
        pager?.setAdapter(photoViewAdapter)
        pager?.setCurrentItem(position)
        pager?.setVisibility(INVISIBLE)
        addOrUpdateSnapshot()
        pager?.setOffscreenPageLimit(2)
        pager?.addOnPageChangeListener(photoViewAdapter)

        if (!isShowIndicator) tv_pager_indicator?.setVisibility(GONE)
        if (!isShowSaveBtn) {
            tv_save?.setVisibility(GONE)
        } else {
            tv_save?.setOnClickListener(this)
        }
    }

    private fun setupPlaceholder() {
        placeholderView!!.visibility = if (isShowPlaceholder) VISIBLE else INVISIBLE
        if (isShowPlaceholder) {
            if (placeholderColor != -1) {
                placeholderView!!.color = placeholderColor
            }
            if (placeholderRadius != -1) {
                placeholderView!!.radius = placeholderRadius
            }
            if (placeholderStrokeColor != -1) {
                placeholderView!!.strokeColor = placeholderStrokeColor
            }
            XPopupUtils.setWidthHeight(placeholderView, rect!!.width(), rect!!.height())
            placeholderView!!.translationX = rect!!.left.toFloat()
            placeholderView!!.translationY = rect!!.top.toFloat()
            placeholderView!!.invalidate()
        }
    }

    private fun showPagerIndicator() {
        if (urls!!.size > 1) {
            val posi = realPosition
            tv_pager_indicator!!.text = (posi + 1).toString() + "/" + urls!!.size
        }
        if (isShowSaveBtn) tv_save!!.visibility = VISIBLE
    }

    private fun addOrUpdateSnapshot() {
        if (srcView == null) return
        if (snapshotView == null) {
            snapshotView = PhotoView(context)
            snapshotView!!.isEnabled = false
            photoViewContainer!!.addView(snapshotView)
            snapshotView!!.scaleType = srcView!!.scaleType
            snapshotView!!.translationX = rect!!.left.toFloat()
            snapshotView!!.translationY = rect!!.top.toFloat()
            XPopupUtils.setWidthHeight(snapshotView, rect!!.width(), rect!!.height())
        }
        val realPosition = realPosition
        snapshotView!!.tag = realPosition
        setupPlaceholder()
        if (imageLoader != null) imageLoader!!.loadSnapshot(
            urls!![realPosition],
            snapshotView!!, srcView
        )
    }

    public override fun doShowAnimation() {
        if (srcView == null) {
            photoViewContainer!!.setBackgroundColor(bgColor)
            pager!!.visibility = VISIBLE
            showPagerIndicator()
            photoViewContainer!!.isReleasing = false
            doAfterShow()
            if (customView != null) {
                customView!!.alpha = 1f
                customView!!.visibility = VISIBLE
            }
            return
        }
        photoViewContainer!!.isReleasing = true
        if (customView != null) customView!!.visibility = VISIBLE
        snapshotView!!.visibility = VISIBLE
        doAfterShow()
        snapshotView!!.post {
            TransitionManager.beginDelayedTransition(
                (snapshotView!!.parent as ViewGroup),
                TransitionSet()
                    .setDuration(animationDuration.toLong())
                    .addTransition(ChangeBounds())
                    .addTransition(ChangeTransform())
                    .addTransition(ChangeImageTransform())
                    .setInterpolator(FastOutSlowInInterpolator())
                    .addListener(object : TransitionListenerAdapter() {
                        override fun onTransitionEnd(transition: Transition) {
                            pager!!.visibility = VISIBLE
                            snapshotView!!.visibility = INVISIBLE
                            showPagerIndicator()
                            photoViewContainer!!.isReleasing = false
                        }
                    })
            )
            snapshotView!!.translationY = 0f
            snapshotView!!.translationX = 0f
            snapshotView!!.scaleType = ImageView.ScaleType.FIT_CENTER
            XPopupUtils.setWidthHeight(
                snapshotView,
                photoViewContainer!!.width,
                photoViewContainer!!.height
            )

            // do shadow anim.
            animateShadowBg(bgColor)
            if (customView != null) customView!!.animate().alpha(1f).setDuration(
                animationDuration.toLong()
            ).start()
        }
    }

    private fun animateShadowBg(endColor: Int) {
        val start = (photoViewContainer!!.background as ColorDrawable).color
        val animator = ValueAnimator.ofFloat(0f, 1f)
        animator.addUpdateListener { animation ->
            photoViewContainer!!.setBackgroundColor(
                (argbEvaluator.evaluate(
                    animation.animatedFraction,
                    start, endColor
                ) as Int)
            )
        }
        animator.setDuration(animationDuration.toLong()).interpolator = LinearInterpolator()
        animator.start()
    }

    public override fun doDismissAnimation() {
        if (srcView == null) {
            photoViewContainer!!.setBackgroundColor(Color.TRANSPARENT)
            doAfterDismiss()
            pager!!.visibility = INVISIBLE
            placeholderView!!.visibility = INVISIBLE
            if (customView != null) {
                customView!!.alpha = 0f
                customView!!.visibility = INVISIBLE
            }
            return
        }
        tv_pager_indicator!!.visibility = INVISIBLE
        tv_save!!.visibility = INVISIBLE
        pager!!.visibility = INVISIBLE
        photoViewContainer!!.isReleasing = true
        snapshotView!!.visibility = VISIBLE
        snapshotView!!.post {
            TransitionManager.beginDelayedTransition(
                (snapshotView!!.parent as ViewGroup),
                TransitionSet()
                    .setDuration(animationDuration.toLong())
                    .addTransition(ChangeBounds())
                    .addTransition(ChangeTransform())
                    .addTransition(ChangeImageTransform())
                    .setInterpolator(FastOutSlowInInterpolator())
                    .addListener(object : TransitionListenerAdapter() {
                        override fun onTransitionStart(transition: Transition) {
                            super.onTransitionStart(transition)
                            doAfterDismiss()
                        }

                        override fun onTransitionEnd(transition: Transition) {
                            pager!!.scaleX = 1f
                            pager!!.scaleY = 1f
                            snapshotView!!.scaleX = 1f
                            snapshotView!!.scaleY = 1f
                            placeholderView!!.visibility = INVISIBLE
                            snapshotView!!.translationX = rect!!.left.toFloat()
                            snapshotView!!.translationY = rect!!.top.toFloat()
                            XPopupUtils.setWidthHeight(
                                snapshotView,
                                rect!!.width(),
                                rect!!.height()
                            )
                        }
                    })
            )
            snapshotView!!.scaleX = 1f
            snapshotView!!.scaleY = 1f
            snapshotView!!.translationX = rect!!.left.toFloat()
            snapshotView!!.translationY = rect!!.top.toFloat()
            snapshotView!!.scaleType = srcView!!.scaleType
            XPopupUtils.setWidthHeight(snapshotView, rect!!.width(), rect!!.height())

            // do shadow anim.
            animateShadowBg(Color.TRANSPARENT)
            if (customView != null) customView!!.animate().alpha(0f).setDuration(
                animationDuration.toLong()
            )
                .setListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        if (customView != null) customView!!.visibility =
                            INVISIBLE
                    }
                })
                .start()
        }
    }

    override fun dismiss() {
        if (popupStatus != PopupStatus.Show) return
        popupStatus = PopupStatus.Dismissing
        doDismissAnimation()
    }

    fun setImageUrls(urls: MutableList<Any>): ImagePop {
        this.urls = urls
        return this
    }

    fun setSrcViewUpdateListener(srcViewUpdateListener: OnSrcViewUpdateListener?): ImagePop {
        this.srcViewUpdateListener = srcViewUpdateListener
        return this
    }

    fun setXPopupImageLoader(imageLoader: SmartGlideImageLoader?): ImagePop {
        this.imageLoader = imageLoader
        return this
    }

    /**
     * 是否显示白色占位区块
     *
     * @param isShow
     * @return
     */
    fun isShowPlaceholder(isShow: Boolean): ImagePop {
        isShowPlaceholder = isShow
        return this
    }

    /**
     * 是否显示页码指示器
     *
     * @param isShow
     * @return
     */
    fun isShowIndicator(isShow: Boolean): ImagePop {
        isShowIndicator = isShow
        return this
    }

    /**
     * 是否显示保存按钮
     *
     * @param isShowSaveBtn
     * @return
     */
    fun isShowSaveButton(isShowSaveBtn: Boolean): ImagePop {
        this.isShowSaveBtn = isShowSaveBtn
        return this
    }

    fun isInfinite(isInfinite: Boolean): ImagePop {
        this.isInfinite = isInfinite
        return this
    }

    fun setPlaceholderColor(color: Int): ImagePop {
        placeholderColor = color
        return this
    }

    fun setPlaceholderRadius(radius: Int): ImagePop {
        placeholderRadius = radius
        return this
    }

    fun setPlaceholderStrokeColor(strokeColor: Int): ImagePop {
        placeholderStrokeColor = strokeColor
        return this
    }

    fun setBgColor(bgColor: Int): ImagePop {
        this.bgColor = bgColor
        return this
    }

    fun setLongPressListener(longPressListener: OnImageViewerLongPressListener?): ImagePop {
        this.longPressListener = longPressListener
        return this
    }

    /**
     * 设置单个使用的源View。单个使用的情况下，无需设置url集合和SrcViewUpdateListener
     *
     * @param srcView
     * @return
     */
    fun setSingleSrcView(srcView: ImageView?, url: Any): ImagePop {
        if (urls == null) {
            urls = ArrayList()
        }
        urls!!.clear()
        urls!!.add(url)
        setSrcView(srcView, 0)
        return this
    }

    fun setSrcView(srcView: ImageView?, position: Int): ImagePop {
        this.srcView = srcView
        this.position = position
        if (srcView != null) {
            val locations = IntArray(2)
            this.srcView!!.getLocationInWindow(locations)
            var left = locations[0] /*- getActivityContentLeft()*/
            if (XPopupUtils.isLayoutRtl(context)) {
                left = -(XPopupUtils.getAppWidth(context) - locations[0] - srcView.width)
                rect = Rect(left, locations[1], left + srcView.width, locations[1] + srcView.height)
            } else {
                rect = Rect(left, locations[1], left + srcView.width, locations[1] + srcView.height)
            }
        }
        return this
    }

    fun updateSrcView(srcView: ImageView?) {
        setSrcView(srcView, position)
        addOrUpdateSnapshot()
    }

    override fun onRelease() {
        dismiss()
    }

    override fun onDragChange(dy: Int, scale: Float, fraction: Float) {
        tv_pager_indicator!!.alpha = 1 - fraction
        if (customView != null) customView!!.alpha = 1 - fraction
        if (isShowSaveBtn) tv_save!!.alpha = 1 - fraction
        photoViewContainer!!.setBackgroundColor(
            (argbEvaluator.evaluate(
                fraction * .8f,
                bgColor,
                Color.TRANSPARENT
            ) as Int)
        )
    }

    override fun onDismiss() {
        super.onDismiss()
        srcView = null
        srcViewUpdateListener = null
    }

    override fun onClick(v: View) {
        if (v === tv_save) save()
    }

    override fun destroy() {
        super.destroy()
        pager!!.removeOnPageChangeListener((pager!!.adapter as PhotoViewAdapter?)!!)
        imageLoader = null
    }

    protected val realPosition: Int
        protected get() = if (isInfinite) position % urls!!.size else position

    /**
     * 保存图片到相册，会自动检查是否有保存权限
     */
    protected fun save() {
        XPermission.create(context, PermissionConstants.STORAGE)
            .callback(object : XPermission.SimpleCallback {
                override fun onGranted() {
                    XPopupUtils.saveBmpToAlbum(context, imageLoader, urls!![realPosition])
                }

                override fun onDenied() {}
            })
            .request()
    }

    inner class PhotoViewAdapter : PagerAdapter(), ViewPager.OnPageChangeListener {
        override fun getCount(): Int {
            return if (isInfinite) 100000 else urls!!.size
        }

        override fun isViewFromObject(view: View, o: Any): Boolean {
            return o === view
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val realPosition = if (isInfinite) position % urls!!.size else position
            //1. build container
            val fl = buildContainer(container.context)
            val progressBar = buildProgressBar(container.context)

            //2. add ImageView，maybe PhotoView or SubsamplingScaleImageView
            val view = imageLoader!!.loadImage(
                realPosition, urls!![realPosition], this@ImagePop,
                snapshotView!!, progressBar
            )

            //3. add View
            fl.addView(
                view,
                LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )

            //4. add ProgressBar
            fl.addView(progressBar)
            container.addView(fl)
            return fl
        }

        private fun buildContainer(context: Context): FrameLayout {
            val fl = FrameLayout(context)
            fl.layoutParams = LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            return fl
        }

        private fun buildProgressBar(context: Context): ProgressBar {
            val progressBar = ProgressBar(context)
            progressBar.isIndeterminate = true
            val size = XPopupUtils.dp2px(container.context, 40f)
            val params = LayoutParams(size, size)
            params.gravity = Gravity.CENTER
            progressBar.layoutParams = params
            progressBar.visibility = GONE
            return progressBar
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
        }

        override fun onPageSelected(i: Int) {
            position = i
            showPagerIndicator()
            //更新srcView
            if (srcViewUpdateListener != null) {
                srcViewUpdateListener!!.onSrcViewUpdate(this@ImagePop, realPosition)
            }
        }

        override fun onPageScrollStateChanged(state: Int) {}
    }
}

private fun OnSrcViewUpdateListener.onSrcViewUpdate(imagePop: ImagePop, realPosition: Int) {

}

private fun SmartGlideImageLoader.loadImage(
    position: Int,
    url: Any,
    popupView: ImagePop,
    snapshot: PhotoView,
    progressBar: ProgressBar
): View? {
    progressBar.visibility = View.VISIBLE
    val imageView: View =
        buildBigImageView(popupView, progressBar, position)!!
    val context = imageView.context
    if (snapshot != null && snapshot.getDrawable() != null && snapshot.getTag() as Int == position) {
        if (imageView is PhotoView) {
            try {
                imageView.setImageDrawable(
                    snapshot.getDrawable().getConstantState()!!.newDrawable()
                )
            } catch (e: Exception) {
            }
        } else {
            (imageView as SubsamplingScaleImageView).setImage(
                ImageSource.bitmap(
                    XPopupUtils.view2Bitmap(
                        snapshot
                    )
                )
            )
        }
    }
    Glide.with(imageView).downloadOnly().load(url)
        .into(object : ImageDownloadTarget() {
            override fun onLoadFailed(errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                progressBar.visibility = View.GONE
                if (imageView is PhotoView) {
                    imageView.setImageResource(-1)
                    (imageView as PhotoView).isZoomable = true
                } else {
                    (imageView as SubsamplingScaleImageView).setImage(ImageSource.resource(-1))
                }
            }

            override fun onResourceReady(
                resource: File,
                transition: com.bumptech.glide.request.transition.Transition<in File?>?
            ) {
                super.onResourceReady(resource, transition)
                val maxW = XPopupUtils.getAppWidth(context) * 2
                val maxH = XPopupUtils.getScreenHeight(context) * 2
                val size = XPopupUtils.getImageSize(resource)
                val degree = XPopupUtils.getRotateDegree(resource.absolutePath)
                //photo view加载
                if (imageView is PhotoView) {
                    progressBar.visibility = View.GONE
                    (imageView as PhotoView).isZoomable = true
                    if (size[0] > maxW || size[1] > maxH) {
                        //TODO: 可能导致大图GIF展示不出来
                        val rawBmp = XPopupUtils.getBitmap(resource, maxW, maxH)
                        imageView.setImageBitmap(
                            XPopupUtils.rotate(
                                rawBmp,
                                degree,
                                size[0] / 2f,
                                size[1] / 2f
                            )
                        )
                        //                                Glide.with(imageView).load(rawBmp)
//                                        .apply(new RequestOptions().error(errImg).override(size[0], size[1])).into(((PhotoView) imageView));
                    } else {
                        Glide.with(imageView).load(resource)
                            .apply(
                                RequestOptions().error(-1).override(
                                    size[0],
                                    size[1]
                                )
                            ).into((imageView as PhotoView)!!)
                    }
                } else {
                    //大图加载
                    val bigImageView = imageView as SubsamplingScaleImageView
                    var longImage = false
                    if (size[1] * 1f / size[0] > XPopupUtils.getScreenHeight(context) * 1f / XPopupUtils.getAppWidth(
                            context
                        )
                    ) {
                        longImage = true
                        bigImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_START)
                    } else {
                        longImage = false
                        bigImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_INSIDE)
                    }
                    val s2 = size[0] * size[1]
                    //优化点击缩放
                    if (s2 != 0) {
                        val i =
                            XPopupUtils.getScreenWidth(context) * XPopupUtils.getAppWidth(context) / s2
                        if (i > 0) bigImageView.setDoubleTapZoomDpi(320 / i)
                    }
                    bigImageView.orientation = degree
                    bigImageView.setOnImageEventListener(
                        SSIVListener(
                            bigImageView,
                            progressBar,
                            -1,
                            longImage,
                            resource
                        )
                    )
                    val preview = XPopupUtils.getBitmap(
                        resource,
                        XPopupUtils.getAppWidth(context),
                        XPopupUtils.getScreenHeight(context)
                    )
                    bigImageView.setImage(
                        ImageSource.uri(Uri.fromFile(resource)).dimensions(
                            size[0], size[1]
                        ),
                        if (preview != null) ImageSource.cachedBitmap(preview) else null
                    )
                }
            }
        })
    return imageView
}

fun buildPhotoView(popupView: ImagePop, snapshotView: PhotoView, realPosition: Int): PhotoView? {
    val photoView = PhotoView(popupView.context)
    photoView.isZoomable = false
    photoView.setOnMatrixChangeListener {
        if (snapshotView != null) {
            val matrix = Matrix()
            photoView.getSuppMatrix(matrix)
            snapshotView.setSuppMatrix(matrix)
        }
    }
    photoView.setOnClickListener { popupView.dismiss() }
    if (popupView.longPressListener != null) {
        photoView.setOnLongClickListener {
            popupView.longPressListener!!.onLongPressed(popupView, realPosition)
            false
        }
    }
    return photoView
}

fun buildBigImageView(
    popupView: ImagePop,
    progressBar: ProgressBar,
    position: Int
): SubsamplingScaleImageView? {
    val ssiv = SubsamplingScaleImageView(popupView.context)
    ssiv.setMinimumDpi(1)
    ssiv.setMaximumDpi(320)
    ssiv.setDoubleTapZoomDuration(250)
    ssiv.setDoubleTapZoomStyle(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER)
    ssiv.setOnStateChangedListener(object : DefaultOnStateChangedListener() {
        override fun onCenterChanged(newCenter: PointF, origin: Int) {
            super.onCenterChanged(newCenter, origin)
            //TODO 同步SubsamplingScaleImageView的滚动给snapshot
//                    Log.e("tag", "y: " + newCenter.y   + " vh: "+ ssiv.getMeasuredHeight()
//                    + "  dy: "+ (newCenter.y - ssiv.getMeasuredHeight()/2));
        }
    })
    ssiv.setOnClickListener { popupView.dismiss() }
    if (popupView.longPressListener != null) {
        ssiv.setOnLongClickListener {
            popupView.longPressListener!!.onLongPressed(popupView, position)
            false
        }
    }
    return ssiv
}

